#include "wifi_config.h"


static const char *TAG = "wifi_config";

WIFICONFIG gs_wificonfig;

char SoftWifiName[32] = "ESP32-Config"; // 初始化 SSID
char SoftWifiPass[64] = "config@123"; // 初始化密码

void initialise_dns(void) {
    // 设置主备DNS
    ip_addr_t dns_main, dns_backup;
    IP_ADDR4(&dns_main, 8, 8, 8, 8);    // Google DNS
    IP_ADDR4(&dns_backup, 208, 67, 222, 222);  // OpenDNS
    dns_setserver(0, &dns_main);
    dns_setserver(1, &dns_backup);
    
    // 启用DNS缓存
    dns_init();
}

bool is_valid_config(const app_config_t *cfg) 
{
    return (strlen(cfg->ssid) > 0) && 
           (strlen(cfg->pass) >= 8) &&
           (cfg->port > 0 && cfg->port <= 65535) &&
           (inet_addr(cfg->ip) != INADDR_NONE);
}

/* 连接监控任务 */
void connection_monitor_task(void *arg) {
    static const char *TAG = "connection_monitor_task";
    while(1) {
        EventBits_t bits = xEventGroupGetBits(gs_wificonfig.handle.wifi_event_group);
        // 增加连接中状态判断
        if (bits & WIFI_PROV_MODE_BIT || 
           (bits & WIFI_CONNECTED_BIT) || 
           (gs_wificonfig.retry_count > 0 && gs_wificonfig.retry_count < MAX_RETRY_COUNT)) {
            vTaskDelay(pdMS_TO_TICKS(3000));
            // ESP_LOGW(TAG, "跳出本次");
            continue;
        }

        // 修改重连逻辑
        if (!(bits & WIFI_CONNECTED_BIT) && is_valid_config(&gs_wificonfig.g_config)) {
            ESP_LOGW(TAG, "触发主动重连");
            gs_wificonfig.retry_count = 0;
            start_sta_mode();
        }
        
        vTaskDelay(pdMS_TO_TICKS(3000));
    }
}





bool ensure_ap_stop() {
    static const char *TAG = "ensure_ap_stop";
    ESP_LOGI(TAG, "开始强制停止AP流程");
    wifi_mode_t current_mode;
    esp_err_t ret = esp_wifi_get_mode(&current_mode);
    
    // 强制模式检查
    if (ret == ESP_OK && (current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA)) {
        // 分阶段停止驱动
        ESP_ERROR_CHECK(esp_wifi_disconnect());
        ESP_ERROR_CHECK(esp_wifi_stop());
        vTaskDelay(pdMS_TO_TICKS(800)); // 延长等待时间
        
        // 强制销毁AP接口
        esp_netif_t *ap_netif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
        if (ap_netif) {
            esp_netif_destroy(ap_netif);
            ESP_LOGI(TAG, "强制销毁AP接口");
        }
        
        // 双保险驱动卸载
        esp_wifi_deinit();
        vTaskDelay(pdMS_TO_TICKS(200));
        wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
        ESP_ERROR_CHECK(esp_wifi_init(&cfg));
        
        // 额外增加状态验证
        esp_wifi_get_mode(&current_mode);
        if (current_mode != WIFI_MODE_NULL) {
            ESP_LOGW(TAG, "驱动状态异常，执行强制恢复");
            esp_restart();
        }
    }
    return true;
}

/* WiFi事件处理 */
void wifi_event_handler(void* arg, esp_event_base_t base, int32_t id, void* data) {
    static const char *TAG = "wifi_event_handler";
    if (base == WIFI_EVENT) {
        switch(id) {
            case WIFI_EVENT_AP_STACONNECTED:   //一个设备连接到 AP
            {
                // 暂停配网超时计时器
                if (gs_wificonfig.handle.prov_timer) {
                    int64_t elapsed = esp_timer_get_time() - esp_timer_get_time();
                    gs_wificonfig.remaining_prov_time -= (elapsed / 1000000);
                    esp_timer_stop(gs_wificonfig.handle.prov_timer);
                    ESP_LOGI(TAG, "暂停计时 | 剩余时间: %d秒", gs_wificonfig.remaining_prov_time);
                }
                gs_wificonfig.connected_sta_count++;
                break;
            }
            // 新增AP断开事件处理
            case WIFI_EVENT_AP_STADISCONNECTED: {
                if (gs_wificonfig.connected_sta_count > 0) gs_wificonfig.connected_sta_count--;
                // 当最后一个设备断开时恢复计时
                if (gs_wificonfig.connected_sta_count == 0 && gs_wificonfig.remaining_prov_time > 0) {
                    ESP_LOGI(TAG, "恢复计时 | 剩余时间: %d秒", gs_wificonfig.remaining_prov_time);
                    esp_timer_start_once(gs_wificonfig.handle.prov_timer, gs_wificonfig.remaining_prov_time * 1000000);
                }
                break;
            }
            case WIFI_EVENT_STA_START:
                ESP_LOGI(TAG, "STA模式就绪");
                break;
            case WIFI_EVENT_STA_CONNECTED:
                ESP_LOGI(TAG, "成功连接AP");
                gs_wificonfig.retry_count = 0;
                break;
            case WIFI_EVENT_STA_DISCONNECTED:    // sta模式连接ap
            {
                wifi_event_sta_disconnected_t* dis = (wifi_event_sta_disconnected_t*)data;
                ESP_LOGW(TAG, "连接断开，原因: %d (%s)", dis->reason, disconnect_reason(dis->reason));
                switch(dis->reason) {
                    case WIFI_REASON_NO_AP_FOUND:
                        ESP_LOGE(TAG, "SSID不存在: %s", gs_wificonfig.g_config.ssid);
                        break;
                    case WIFI_REASON_AUTH_FAIL:
                        ESP_LOGE(TAG, "密码错误或加密方式不匹配");
                        break;
                    default:
                        break;
                }
                if (gs_wificonfig.retry_count < MAX_RETRY_COUNT){
                    ESP_LOGI(TAG, "尝试重连 (%d/%d)", ++gs_wificonfig.retry_count, MAX_RETRY_COUNT);
                    esp_wifi_connect();
                } else {
                    xEventGroupClearBits(gs_wificonfig.handle.wifi_event_group, WIFI_CONNECTED_BIT);
                    ESP_LOGE(TAG, "超过最大重试次数，进入配网模式");
                    start_provisioning(PROV_TIMEOUT_RETRY);
                }
                esp_wifi_clear_ap_list();
                break;
            }

            case WIFI_EVENT_AP_START:
                xEventGroupSetBits(gs_wificonfig.handle.wifi_event_group, WIFI_AP_START_BIT);
                xEventGroupClearBits(gs_wificonfig.handle.wifi_event_group, WIFI_AP_STOP_BIT);
                ESP_LOGI(TAG, "AP模式就绪 | 内存: %" PRIu32, esp_get_free_heap_size());
                break;

            case WIFI_EVENT_AP_STOP:
                xEventGroupClearBits(gs_wificonfig.handle.wifi_event_group, WIFI_AP_START_BIT);
                xEventGroupSetBits(gs_wificonfig.handle.wifi_event_group, WIFI_AP_STOP_BIT);
                esp_netif_t *ap_netif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
                if (ap_netif) {
                    esp_netif_destroy(ap_netif);
                    ESP_LOGI(TAG, "AP接口已销毁");
                }
                break;
        }
    }
    else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) data;
        ESP_LOGI(TAG, "获取到IP: " IPSTR, IP2STR(&event->ip_info.ip));
        xEventGroupSetBits(gs_wificonfig.handle.wifi_event_group, WIFI_CONNECTED_BIT);
        Http_Ota_Init();
        // 启动TCP客户端任务
        if (gs_wificonfig.handle.tcp_task_handle == NULL) {
            xTaskCreate(tcp_client_task, "tcp_client", 4096, NULL, configMAX_PRIORITIES - 1, &gs_wificonfig.handle.tcp_task_handle);
        }
    }
}

/* NVS初始化增强 */
esp_err_t init_nvs() {
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_LOGI(TAG, "NVS分区需要擦除");
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    return ret;
}

/* 配置加载带校验 */
esp_err_t load_config(app_config_t *cfg) {
    nvs_handle_t handle;
    static const char *TAG = "load_config";
    ESP_LOGI(TAG, "尝试加载配置...");

    esp_err_t ret = nvs_open(NVS_NAMESPACE, NVS_READONLY, &handle);
    if (ret != ESP_OK) {
        ESP_LOGI(TAG, "未找到NVS命名空间，使用默认配置");
        return ret;
    }

    size_t len = sizeof(cfg->ssid);
    nvs_get_str(handle, WIFI_SSID_KEY, cfg->ssid, &len);
    memcpy(SoftWifiName,cfg->ssid,len);
    // sprintf(SoftWifiName,"%s_g",cfg->ssid);
    char temp_buf[34]; // 临时缓冲区（32+2）
    snprintf(temp_buf, sizeof(temp_buf), "%s_g", SoftWifiName);
    strncpy(SoftWifiName, temp_buf, sizeof(SoftWifiName)-1);
    SoftWifiName[sizeof(SoftWifiName)-1] = '\0'; // 强制终止
    
    len = sizeof(cfg->pass);
    nvs_get_str(handle, WIFI_PASS_KEY, cfg->pass, &len);
    memcpy(SoftWifiPass,cfg->pass,len);
    
    len = sizeof(cfg->ip);
    nvs_get_str(handle, SERVER_IP_KEY, cfg->ip, &len);
    
    nvs_get_i32(handle, SERVER_PORT_KEY, &cfg->port);
    nvs_close(handle);

    ESP_LOGI(TAG, "加载配置成功:");
    ESP_LOGI(TAG, "SSID: [%s]", cfg->ssid);
    ESP_LOGI(TAG, "PASS: [%s]", cfg->pass);
    ESP_LOGI(TAG, "服务器: %s:%" PRId32, cfg->ip, cfg->port);
    return ESP_OK;
}

/* 配置保存带重试 */
esp_err_t save_config(const app_config_t *cfg) {
    ESP_LOGI(TAG, "保存配置到NVS...");
    
    for (int i = 0; i < 3; i++) {
        nvs_handle_t handle;
        esp_err_t ret = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle);
        if (ret != ESP_OK) {
            // vTaskDelay(pdMS_TO_TICKS(100));
            continue;
        }

        nvs_set_str(handle, WIFI_SSID_KEY, cfg->ssid);
        nvs_set_str(handle, WIFI_PASS_KEY, cfg->pass);
        nvs_set_str(handle, SERVER_IP_KEY, cfg->ip);
        nvs_set_i32(handle, SERVER_PORT_KEY, cfg->port);

        ret = nvs_commit(handle);
        nvs_close(handle);
        
        if (ret == ESP_OK) {
            ESP_LOGI(TAG, "配置保存成功");
            return ESP_OK;
        }
        // vTaskDelay(pdMS_TO_TICKS(50));
    }
    
    ESP_LOGE(TAG, "配置保存失败!");
    return ESP_FAIL;
}

/* 配网页面处理 */
esp_err_t root_handler(httpd_req_t *req) {
    const char* html = "<!DOCTYPE html><html><head>"
                       "<meta name='viewport' content='width=320'>"
                       "<style>body{font-family:Arial;margin:20px}input{display:block;margin:10px 0;padding:8px;width:95%}button{background:#007bff;color:white;border:none;padding:10px 20px}</style></head>"
                       "<body><h2>设备配网</h2>"
                       "<form method=post action=/config>"
                       "<input name=ssid placeholder='WiFi名称' required>"
                       "<input type=password name=pass placeholder='密码' minlength=8 required>"
                       "<input name=ip placeholder='服务器IP' pattern='^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$' required>"
                       "<input name=port type=number placeholder='端口' min=1 max=65535 required>"
                       "<button type=submit>保存配置</button></form></body></html>";
    
    httpd_resp_set_type(req, "text/html");
    httpd_resp_send(req, html, HTTPD_RESP_USE_STRLEN);
    return ESP_OK;
}

/* 配置提交处理 */
esp_err_t config_handler(httpd_req_t *req) 
{
    char buf[512];
    int total = 0;
    int remaining = req->content_len;
    while (remaining > 0) {
        int recv = httpd_req_recv(req, buf + total, MIN(remaining, sizeof(buf)-total-1));
        if (recv <= 0) {
            if (recv == HTTPD_SOCK_ERR_TIMEOUT) continue;
            ESP_LOGE(TAG, "接收数据失败: %d", recv);
            httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "接收失败");
            return ESP_FAIL;
        }
        total += recv;
        remaining -= recv;
    }
    buf[total] = '\0';

    ESP_LOGI(TAG, "收到配置数据: %s", buf);

    // 参数解析带校验
    char *ssid = strstr(buf, "ssid=");
    char *pass = strstr(buf, "pass=");
    char *ip = strstr(buf, "ip=");
    char *port = strstr(buf, "port=");

    if (!ssid || !pass || !ip || !port) {
        ESP_LOGE(TAG, "缺少必要参数");
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "参数不完整");
        return ESP_FAIL;
    }

    memset(&gs_wificonfig.g_config, 0, sizeof(app_config_t));
    sscanf(ssid+5, "%31[^&]", gs_wificonfig.g_config.ssid);
    sscanf(pass+5, "%63[^&]", gs_wificonfig.g_config.pass);
    sscanf(ip+3, "%15[^&]", gs_wificonfig.g_config.ip);
    sscanf(port+5, "%" SCNd32, &gs_wificonfig.g_config.port);

    // 参数有效性检查
    if (strlen(gs_wificonfig.g_config.ssid) < 1 || strlen(gs_wificonfig.g_config.pass) < 8 || 
        gs_wificonfig.g_config.port <= 0 || gs_wificonfig.g_config.port > 65535) {
        ESP_LOGE(TAG, "参数校验失败");
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "参数无效");
        return ESP_FAIL;
    }

    if (save_config(&gs_wificonfig.g_config) != ESP_OK) {
        httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "保存失败");
        return ESP_FAIL;
    }

    // 修改响应内容，不重启设备
    httpd_resp_send(req, "配置保存成功，正在连接网络...", HTTPD_RESP_USE_STRLEN);
    ESP_LOGI(TAG, "配置验证通过，开始连接网络");
    xEventGroupClearBits(gs_wificonfig.handle.wifi_event_group, WIFI_PROV_MODE_BIT);
    // 停止配网相关资源
    if (gs_wificonfig.handle.prov_timer) {
        esp_timer_stop(gs_wificonfig.handle.prov_timer);
        esp_timer_delete(gs_wificonfig.handle.prov_timer);
        gs_wificonfig.handle.prov_timer = NULL;
    }
    if (gs_wificonfig.handle.server) {
        httpd_stop(gs_wificonfig.handle.server);
        gs_wificonfig.handle.server = NULL;
    }

    ESP_LOGI(TAG, "停止配网资源成功");
    

    // 启动STA模式
    start_sta_mode();

    return ESP_OK;
}

char* build_json_payload_cjson(const uint8_t* data, size_t len) {
    if (!data || len == 0) return NULL;

    // 创建根 JSON 对象
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "Topic", "/RFID/ReadBolak");

    // 创建 Payload 对象
    cJSON *payload = cJSON_CreateObject();

    // 创建 DataArray 数组
    cJSON *data_array = cJSON_CreateArray();
    for (size_t i = 0; i < len; i++) {
        cJSON_AddItemToArray(data_array, cJSON_CreateNumber(data[i]));
    }

    // 添加 DataArray 到 Payload
    cJSON_AddItemToObject(payload, "DataArray", data_array);

    // 创建 ExtraInfo 子对象
    cJSON *extra_info = cJSON_CreateObject();
    cJSON_AddStringToObject(extra_info, "Key", "Value");

    // 添加 ExtraInfo 到 Payload
    cJSON_AddStringToObject(payload, "CardID", (const char *)gs_rfid.card_id_str);


    cJSON_AddNumberToObject(payload, "Bolck", gs_rfid.bolck_addr);

    // 添加 Payload 到 root
    cJSON_AddItemToObject(root, "Payload", payload);

    // 生成 JSON 字符串
    char *json_str = cJSON_PrintUnformatted(root);
    ESP_LOGW(TAG, "send: %s", json_str);

    // 释放 cJSON 结构
    cJSON_Delete(root);

    return json_str; // 需要调用者手动 free() 释放
}

// // 高性能版本（减少snprintf调用次数）
char* build_json_payload_optimized(const uint8_t* data, size_t len) {
    if (!data || len == 0) return NULL;

    // 预计算精确长度
    size_t total_len = 50; // 基础长度
    for (size_t i=0; i<len; i++) {
        total_len += (data[i]>99) ? 3 : 
                    (data[i]>9)  ? 2 : 1;
    }
    total_len += len; // 逗号数量

    char* buf = malloc(total_len);
    char* ptr = buf;
    
    // 手动构建提高效率
    ptr += sprintf(ptr, "{\"Topic\":\"/RFID/ReadBolak\",\"Payload\":[");
    for (size_t i=0; i<len; i++) {
        if(i != 0) *ptr++ = ',';
        ptr += sprintf(ptr, "%d", data[i]);
    }
    strcpy(ptr, "]}");
    ESP_LOGW(TAG,"send:%s",buf);
    return buf;
}

void reverse_array(uint8_t *arr, int len) {
    for(int i=0; i<len/2; i++) {
        uint8_t temp = arr[i];
        arr[i] = arr[len-1-i];
        arr[len-1-i] = temp;
    }
}

char* build_versioned_payload(uint32_t version, const uint8_t* data, size_t data_len) {
    uint8_t version_digits[8];
    int version_len = 0;
    
    // 版本号分解
    do {
        version_digits[version_len++] = version % 10;
        version /= 10;
    } while (version > 0 && version_len < 8);
    reverse_array(version_digits, version_len);

    // 计算总长度
    size_t total_len = 64 + (data_len + version_len) * 4; // 安全余量
    
    char* buf = malloc(total_len);
    char* ptr = buf;
    
    // 构建JSON
    ptr += snprintf(ptr, total_len, "{\"Topic\":\"/RFID/Version\",\"Payload\":[");
    for (int i=0; i<version_len; i++) {
        ptr += snprintf(ptr, total_len-(ptr-buf), "%s%d", (i>0)?",":"", version_digits[i]);
    }
    if (data && data_len >0) {
        ptr += snprintf(ptr, total_len-(ptr-buf), ",");
        for (size_t i=0; i<data_len; i++) {
            ptr += snprintf(ptr, total_len-(ptr-buf), "%s%d", (i>0)?",":"", data[i]);
        }
    }
    strcpy(ptr, "]}");
    
    return buf;
}

void tcp_client_task(void *pvParameters) {
    ESP_LOGI(TAG, "TCP任务启动");
    // uint32_t current_version = CURRENT_VERSION;
    uint8_t version_buff[16];
    sprintf((char *)version_buff,"%d",CURRENT_VERSION);
    int retry_delay_ms = INITIAL_RETRY_DELAY_MS;
    TickType_t last_heartbeat = 0;
    cJSON *params_version_cjson = cJSON_CreateObject();
    cJSON_AddStringToObject(params_version_cjson,"Topic","/RFID/Version");
    cJSON_AddStringToObject(params_version_cjson, "Version", (const char *)version_buff);
    char *version_str = cJSON_PrintUnformatted(params_version_cjson);
    free(params_version_cjson);

    while (1) {
        // 指数退避延迟
        if (retry_delay_ms > INITIAL_RETRY_DELAY_MS) {
            ESP_LOGW(TAG, "等待重连: %dms", retry_delay_ms);
            vTaskDelay(pdMS_TO_TICKS(retry_delay_ms));
            retry_delay_ms = MIN(retry_delay_ms * 2, MAX_RETRY_DELAY_MS);
        }

        // 创建socket（带资源监控）
        ESP_LOGD(TAG, "可用内存: %"PRIu32"字节", esp_get_free_heap_size());
        int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
        if (sock < 0) {
            ESP_LOGE(TAG, "创建socket失败: %s", strerror(errno));
            continue;
        }

        // 设置socket选项
        int reuse = 1;
        setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
        struct timeval tv = {.tv_sec = 10, .tv_usec = 0};
        setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
        setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));

        // 配置目标地址
        struct sockaddr_in dest_addr = {
            .sin_family = AF_INET,
            .sin_port = htons(gs_wificonfig.g_config.port)
        };
        inet_pton(AF_INET, gs_wificonfig.g_config.ip, &dest_addr.sin_addr);

        // 非阻塞连接
        int flags = fcntl(sock, F_GETFL, 0);
        fcntl(sock, F_SETFL, flags | O_NONBLOCK);
        
        int conn_ret = connect(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
        if (conn_ret == 0) {
            ESP_LOGI(TAG, "立即连接成功");
            goto connection_established;
        }

        // 异步连接处理
        fd_set fdset;
        FD_ZERO(&fdset);
        FD_SET(sock, &fdset);
        struct timeval timeout = {.tv_sec = 5, .tv_usec = 0};
        
        if (select(sock + 1, NULL, &fdset, NULL, &timeout) <= 0) {
            ESP_LOGE(TAG, "连接超时");
            CLOSE_SOCKET(sock);
            continue;
        }

        // 验证连接状态
        int sockerr;
        socklen_t len = sizeof(sockerr);
        getsockopt(sock, SOL_SOCKET, SO_ERROR, &sockerr, &len);
        if (sockerr != 0) {
            ESP_LOGE(TAG, "连接错误: %s", strerror(sockerr));
            CLOSE_SOCKET(sock);
            continue;
        }

connection_established:
        // 恢复阻塞模式
        fcntl(sock, F_SETFL, flags);
        ESP_LOGW(TAG, "成功连接到 %s:%" PRId32, 
            gs_wificonfig.g_config.ip, 
            (int32_t)gs_wificonfig.g_config.port);
        retry_delay_ms = INITIAL_RETRY_DELAY_MS; // 重置退避计时

        // 主通信循环   {"Topic":"SubscriptionAdd","Payload":["/dev/WriteRFID"]}
        uint8_t sendtopicbuff[64] = "{\"Topic\":\"SubscriptionAdd\",\"Payload\":[\"/dev/OperateRFID\"]}";
        if(send(sock,sendtopicbuff,strlen((char*)sendtopicbuff),0))
        {

        }
        while (1) {
            // 发送心跳包
            if (xTaskGetTickCount() - last_heartbeat > pdMS_TO_TICKS(HEARTBEAT_INTERVAL_MS)) {
                if (send(sock, version_str, strlen((char *)version_str), 0) < 0) {
                    ESP_LOGE(TAG, "心跳发送失败");
                    // free(hb_payload);
                    break;
                }
                // free(hb_payload);
                last_heartbeat = xTaskGetTickCount();
            }

            // 发送业务数据
            if (gs_rfid.bolck_flag) {
                // char *payload = build_json_payload_optimized(gs_rfid.bolck_data, sizeof(gs_rfid.bolck_data));
                cJSON *root = cJSON_CreateObject();
                cJSON_AddStringToObject(root,"Topic","/RFID/ReadBolak");
                 // 创建 Payload 对象
                cJSON *payload = cJSON_CreateObject();

                // 创建 DataArray 数组
                cJSON *data_array = cJSON_CreateArray();
                for (size_t i = 0; i < 16; i++) {
                    cJSON_AddItemToArray(data_array, cJSON_CreateNumber(gs_rfid.bolck_data[i]));
                }
                // 添加 DataArray 到 Payload
                cJSON_AddItemToObject(payload, "DataArray", data_array);
                cJSON_AddStringToObject(payload, "CardID", (const char *)gs_rfid.card_id_str);
                // 添加 Payload 到 root
                cJSON_AddItemToObject(root, "Payload", payload);

                if (send(sock, cJSON_PrintUnformatted(root), strlen(cJSON_PrintUnformatted(root)), 0) < 0) {
                    ESP_LOGE(TAG, "数据发送失败");
                    free(payload);
                    free(root);
                    free(data_array);
                    break;
                }
                free(payload);
                free(root);
                free(data_array);
                gs_rfid.bolck_flag = false;
                BeepOn();
                vTaskDelay(pdMS_TO_TICKS(200));
                BeepOff();
            }
            else if(gs_rfid.car_state == CAR_WRITE_BLAKE_SUCCESS)
            {
                cJSON *root = cJSON_CreateObject();
                cJSON_AddStringToObject(root,"Topic","/RFID/Reply");
                cJSON *payload = cJSON_CreateObject();
                cJSON_AddStringToObject(payload,"Cmd","Write");
                cJSON_AddBoolToObject(payload,"res",1);
                cJSON_AddStringToObject(payload, "CardID", (const char *)gs_rfid.card_id_str);
                cJSON_AddNumberToObject(payload,"Bolck",gs_rfid.bolck_addr);
                cJSON_AddItemToObject(root, "Payload", payload);
                if (send(sock, cJSON_PrintUnformatted(root), strlen(cJSON_PrintUnformatted(root)), 0) < 0) {
                    ESP_LOGE(TAG, "数据发送失败");
                    free(payload);
                    free(root);
                    gs_rfid.car_state =  CAR_WAIT_OPERATE;
                    break;
                }
                free(payload);
                free(root);
                gs_rfid.car_state =  CAR_WAIT_OPERATE;
            }
            else if(gs_rfid.car_state == CAR_WRITE_BLAKE_FAIL)
            {
                cJSON *root = cJSON_CreateObject();
                cJSON_AddStringToObject(root,"Topic","/RFID/Reply");
                cJSON *payload = cJSON_CreateObject();
                cJSON_AddStringToObject(payload,"Cmd","Write");
                cJSON_AddBoolToObject(payload,"res",0);
                cJSON_AddStringToObject(payload, "CardID", (const char *)gs_rfid.card_id_str);
                cJSON_AddNumberToObject(payload,"Bolck",gs_rfid.bolck_addr);
                cJSON_AddItemToObject(root, "Payload", payload);

                if (send(sock, cJSON_PrintUnformatted(root), strlen(cJSON_PrintUnformatted(root)), 0) < 0) {
                    ESP_LOGE(TAG, "数据发送失败");
                    free(payload);
                    free(root);
                    gs_rfid.car_state =  CAR_WAIT_OPERATE;
                    break;
                }
                free(payload);
                free(root);
                gs_rfid.car_state =  CAR_WAIT_OPERATE;
            }
            else if(gs_rfid.car_state == CAR_READ_BLAKE_FAIL)
            {
                cJSON *root = cJSON_CreateObject();
                cJSON_AddStringToObject(root,"Topic","/RFID/Reply");
                cJSON *payload = cJSON_CreateObject();
                cJSON_AddStringToObject(payload,"Cmd","Read");
                cJSON_AddNumberToObject(payload,"Bolck",gs_rfid.bolck_addr);
                cJSON *data_array = cJSON_CreateArray();
                cJSON_AddStringToObject(payload, "CardID", (const char *)gs_rfid.card_id_str);
                cJSON_AddItemToObject(payload, "DataArray", data_array);
                cJSON_AddItemToObject(root, "Payload", payload);
                if (send(sock, cJSON_PrintUnformatted(root), strlen(cJSON_PrintUnformatted(root)), 0) < 0) {
                    ESP_LOGE(TAG, "数据发送失败");
                    free(payload);
                    free(root);
                    free(data_array);
                    gs_rfid.car_state =  CAR_WAIT_OPERATE;
                    break;
                }
                free(payload);
                free(root);
                free(data_array);
                gs_rfid.car_state =  CAR_WAIT_OPERATE;
            }
            else if(gs_rfid.car_state == CAR_READ_BLAKE_SUCCESS)
            {
                cJSON *root = cJSON_CreateObject();
                cJSON_AddStringToObject(root,"Topic","/RFID/Reply");
                cJSON *payload = cJSON_CreateObject();
                cJSON_AddStringToObject(payload,"Cmd","Read");
                cJSON_AddStringToObject(payload, "CardID", (const char *)gs_rfid.card_id_str);
                cJSON_AddNumberToObject(payload,"Bolck",gs_rfid.bolck_addr);
                cJSON *data_array = cJSON_CreateArray();
                for (int i = 0; i < gs_rfid.read_cnt; i++) {
                    cJSON_AddItemToArray(data_array, cJSON_CreateNumber(gs_rfid.read_date[i]));
                }
                cJSON_AddItemToObject(payload, "DataArray", data_array);
                cJSON_AddItemToObject(root, "Payload", payload);
                if (send(sock, cJSON_PrintUnformatted(root), strlen(cJSON_PrintUnformatted(root)), 0) < 0) {
                    ESP_LOGE(TAG, "数据发送失败");
                    free(root);
                    free(payload);
                    free(data_array);
                    gs_rfid.car_state =  CAR_WAIT_OPERATE;
                    break;
                }
                free(root);
                free(payload);
                free(data_array);
                gs_rfid.car_state =  CAR_WAIT_OPERATE;
            }

            

            // 接收处理（非阻塞）
            char recv_buf[128];
            int recv_len = recv(sock, recv_buf, sizeof(recv_buf)-1, MSG_DONTWAIT);
            if (recv_len > 0) {
                recv_buf[recv_len] = '\0';
                ESP_LOGI(TAG, "收到响应: %s", recv_buf);
                cJSON *json = cJSON_Parse(recv_buf);
                if(!json){
                    ESP_LOGE(TAG, "JSON解析失败! 原始数据");
                }
                else{
                    if (cJSON_GetObjectItem(json, "Topic")) 
                    {
                        cJSON *topic = cJSON_GetObjectItem(json, "Topic");
                        //ESP_LOGI(TAG, "11Topic: %s", topic->valuestring);
                        if (cJSON_IsString(topic) && (topic->valuestring != NULL)) 
                        {
                            if(strcmp(topic->valuestring, "/RFID/OperateRFID") == 0)
                            {
                                ESP_LOGI(TAG, "Topic: %s size = %d", topic->valuestring,strlen(topic->valuestring));
                                cJSON *Payload_json = cJSON_GetObjectItem(json,"Playload");
                                if(Payload_json != NULL){
                                    if(cJSON_GetObjectItem(Payload_json,"Cmd") && cJSON_GetObjectItem(Payload_json,"Bolck"))//&& cJSON_GetObjectItem(Payload_json,"data")
                                    {
                                        gs_rfid.bolck_addr = cJSON_GetObjectItem(Payload_json,"Bolck")->valueint;
                                        if(strcmp(cJSON_GetObjectItem(Payload_json,"Cmd")->valuestring,"Read") == 0){
                                            gs_rfid.car_state = CAR_READ_BLAKE_DATA;
                                            ESP_LOGI(TAG,"读%d块数据",gs_rfid.bolck_addr);
                                        }
                                        else if(strcmp(cJSON_GetObjectItem(Payload_json,"Cmd")->valuestring,"Write") == 0 && cJSON_HasObjectItem(Payload_json, "data"))
                                        {
                                            ESP_LOGI(TAG,"写%d块数据",gs_rfid.bolck_addr);
                                            cJSON *data_ = cJSON_GetObjectItemCaseSensitive(Payload_json, "data");
                                            if(cJSON_GetArraySize(data_) == 16)
                                            {
                                                printf("Payload: ");
                                                gs_rfid.write_cnt = 0;
                                                for (int i = 0; i < cJSON_GetArraySize(data_); i++) {
                                                    cJSON *payload_item = cJSON_GetArrayItem(data_, i);
                                                    if (cJSON_IsNumber(payload_item)) {
                                                        printf("%d ", payload_item->valueint);
                                                        gs_rfid.write_data[gs_rfid.write_cnt++] = payload_item->valueint;
                                                    }
                                                }
                                                printf("\n");
                                                gs_rfid.car_state = CAR_WRITE_BLAKE_DATA;
                                            }
                                            else{
                                                ESP_LOGE(TAG,"写数据长度不对,需要16个字节，但是只有 %d",cJSON_GetArraySize(data_));
                                                gs_rfid.car_state = CAR_WRITE_BLAKE_FAIL;

                                            }
                                            
                                            
                                        }
                                        else{
                                            gs_rfid.bolck_addr = 0;
                                            ESP_LOGE(TAG,"没有对应的Cmd的指令");
                                        }
                                    }
                                    
                                }
                                else{
                                    printf("sajnxjsncsdmcdjsncvjd");    
                                }
                            }
                            else{
                                printf("sajnxjsn");
                            }




                            // if (strcmp(topic->valuestring, "/RFID/OperateRFID") == 0 && cJSON_HasObjectItem(json, "Payload")) {
                            //     cJSON *payload = cJSON_GetObjectItemCaseSensitive(json, "Payload");
                            //     if (cJSON_IsArray(payload)) {
                            //         uint8_t temp_buff[32];
                            //         uint8_t temp_cnt = 0;
                            //         uint16_t crc_sum = 0;
                            //         /// ===========写到这里   首字节（0x11 写  0x22 读） 块  数据（16位） 校验和(2字节)  1+1+16+2 = 20
                            //         if(cJSON_GetArraySize(payload) == 20)
                            //         {
                            //             printf("Payload: ");
                            //             for (int i = 0; i < cJSON_GetArraySize(payload); i++) {
                            //                 cJSON *payload_item = cJSON_GetArrayItem(payload, i);
                            //                 if (cJSON_IsNumber(payload_item)) {
                            //                     printf("%d ", payload_item->valueint);
                            //                     temp_buff[temp_cnt++] = payload_item->valueint;
                            //                     if(i<18){crc_sum += payload_item->valueint;}
                            //                 }
                            //             }
                            //             printf("\n");
                            //             uint16_t cec_rece =  (temp_buff[18] << 8) | temp_buff[19];
                            //             if(crc_sum ==  cec_rece && gs_rfid.car_state == CAR_WAIT_OPERATE)
                            //             {
                            //                 if(temp_buff[0] == 0x11){gs_rfid.car_state = CAR_WRITE_BLAKE_DATA;ESP_LOGI(TAG,"写操作");}else if(temp_buff[0]==0x22){gs_rfid.car_state = CAR_READ_BLAKE_DATA;ESP_LOGI(TAG,"读操作");}else{ESP_IOGE(TAG,"首字母错误指令");continue;}
                            //                 if(temp_buff[1] <= 67){gs_rfid.bolck_addr = temp_buff[1];ESP_LOGI(TAG, "操作块: %d", gs_rfid.bolck_addr);}else{ESP_IOGE(TAG,"操作块超出地址");continue;}
                                            
                            //             }
                            //             else if(crc_sum ==  cec_rece){
                            //                 ESP_IOGE(TAG,"数据校验出错");
                            //             }
                            //             else{
                            //                 ESP_IOGE(TAG,"当前卡状态错误");
                            //             }
                                        
                            //         }
                            //         else{
                            //             ESP_LOGE(TAG,"接收到数据有误");
                            //         }
                                    
                            //     }
                            // } else {
                            //     printf("\"Payload\" field does not exist.\n");
                            // }
                        }
                        else
                        {
                            
                        }
                    } else {
                        ESP_LOGE(TAG, "没有解析到Topic");
                    }
                }
            }

            vTaskDelay(pdMS_TO_TICKS(TCP_SEND_INTERVAL_MS));
        }

        CLOSE_SOCKET(sock);
        ESP_LOGW(TAG, "连接中断");
    }

    vTaskDelete(NULL);
}


void clear_network_interfaces() {
    // 分阶段清理
    ESP_LOGI(TAG, "开始清理网络资源...");
    
    // 1. 停止TCP任务
    if (gs_wificonfig.handle.tcp_task_handle) {
        vTaskDelete(gs_wificonfig.handle.tcp_task_handle);
        gs_wificonfig.handle.tcp_task_handle = NULL;
        ESP_LOGI(TAG, "TCP任务已停止");
    }
    
    // 2. 停止Web服务
    if (gs_wificonfig.handle.server) {
        httpd_stop(gs_wificonfig.handle.server);
        gs_wificonfig.handle.server = NULL;
        ESP_LOGI(TAG, "Web服务已停止");
    }
    
    // 3. 停止WiFi驱动
    esp_wifi_stop();
    esp_wifi_deinit();
    vTaskDelay(pdMS_TO_TICKS(200));


    // 4. 销毁网络接口
    esp_netif_t *ap_netif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
    if (ap_netif) {
        esp_netif_destroy(ap_netif);
        ESP_LOGI(TAG, "AP接口已销毁");
    }

    esp_netif_t *sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
    if (sta_netif) {
        esp_netif_destroy(sta_netif);
        ESP_LOGI(TAG, "STA接口已销毁");
    }

    // 5. 重启WiFi驱动
    esp_wifi_deinit();
    vTaskDelay(pdMS_TO_TICKS(100));
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg);
    ESP_LOGI(TAG, "WiFi驱动已重置");
}

/* 启动Web服务器增强 */
esp_err_t start_webserver(void) {

    ESP_LOGI(TAG, "正在初始化网络服务栈...");
    initialise_dns();
    esp_netif_init();
    esp_event_loop_create_default();

    if (gs_wificonfig.handle.server) {
        ESP_LOGI(TAG, "停止现有Web服务");
        httpd_stop(gs_wificonfig.handle.server);
        // vTaskDelay(pdMS_TO_TICKS(1000));
    }

    // 修改服务器配置
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    config.server_port = 80;
    config.ctrl_port = 32768;
    config.max_open_sockets = 5;  // 增加连接数
    config.stack_size = 16384;    // 增大栈空间
    config.lru_purge_enable = true;
    config.enable_so_linger = true;
    config.linger_timeout = 5;

    ESP_LOGI(TAG, "启动Web服务器...");
    esp_err_t ret = httpd_start(&gs_wificonfig.handle.server, &config);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "服务器启动失败: %s", esp_err_to_name(ret));
        return ret;
    }

    httpd_uri_t root_uri = {
        .uri = "/",
        .method = HTTP_GET,
        .handler = root_handler
    };

    httpd_uri_t config_uri = {
        .uri = "/config",
        .method = HTTP_POST,
        .handler = config_handler
    };

    httpd_register_uri_handler(gs_wificonfig.handle.server, &root_uri);
    httpd_register_uri_handler(gs_wificonfig.handle.server, &config_uri);
    ESP_LOGI(TAG, "Web服务已就绪");
    return ESP_OK;
}

void start_sta_mode(void) {
    static const char *TAG = "start_sta";
    esp_wifi_deinit();
    vTaskDelay(pdMS_TO_TICKS(200));
    wifi_init_config_t wifi_init_cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_cfg));
    esp_netif_t *sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
    if (!sta_netif) {
        sta_netif = esp_netif_create_default_wifi_sta();
        assert(sta_netif);
        ESP_LOGI(TAG, "新建STA接口完成");
    }
    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
    wifi_config_t wifi_cfg = {0};
    strlcpy((char*)wifi_cfg.sta.ssid, gs_wificonfig.g_config.ssid, sizeof(wifi_cfg.sta.ssid));
    strlcpy((char*)wifi_cfg.sta.password, gs_wificonfig.g_config.pass, sizeof(wifi_cfg.sta.password));
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_cfg));
    vTaskDelay(pdMS_TO_TICKS(300));
    ESP_ERROR_CHECK(esp_wifi_start());
    
    esp_err_t conn_ret = esp_wifi_connect();
    if (conn_ret != ESP_OK) {
        ESP_LOGE(TAG, "连接初始化失败:0x%x，执行紧急恢复", conn_ret);
        // clear_network_interfaces();
        // start_provisioning(PROV_TIMEOUT_RETRY);
        return;
    }
}

void prov_timeout_cb(void* arg) {
    static const char *TAG = "配网超时处理";
    if (gs_wificonfig.connected_sta_count > 0) {
        ESP_LOGI(TAG, "有设备在线，保持配网模式");
        return;
    }
    if (xEventGroupGetBits(gs_wificonfig.handle.wifi_event_group) & WIFI_CONNECTED_BIT) {
        ESP_LOGI(TAG, "已有有效连接，放弃重连");
        return;
    }
    memset(&gs_wificonfig.g_config, 0, sizeof(gs_wificonfig.g_config));
    if (load_config(&gs_wificonfig.g_config) == ESP_OK && is_valid_config(&gs_wificonfig.g_config)) {
        ESP_LOGI(TAG, "发现有效配置，准备STA连接");
        clear_network_interfaces();
        vTaskDelay(pdMS_TO_TICKS(500));
        xEventGroupClearBits(gs_wificonfig.handle.wifi_event_group, WIFI_PROV_MODE_BIT);
        start_sta_mode();
    } else {
        xEventGroupClearBits(gs_wificonfig.handle.wifi_event_group, WIFI_PROV_MODE_BIT);
        ESP_LOGI(TAG, "保持配网模式");
        start_provisioning(PROV_TIMEOUT_FIRST);
    }
}



/* 调整配网模式启动流程 */
void start_provisioning(int timeout) {
    static const char *TAG = "start_provisioning";
    ESP_LOGI(TAG, "===== 进入配网模式 =====");
    // 初始化连接状态
    gs_wificonfig.connected_sta_count = 0;
    gs_wificonfig.remaining_prov_time = timeout;
    xEventGroupSetBits(gs_wificonfig.handle.wifi_event_group, WIFI_PROV_MODE_BIT);
    esp_wifi_stop();  
    vTaskDelay(pdMS_TO_TICKS(500)); 
    esp_wifi_deinit(); 
    clear_network_interfaces();
    esp_wifi_set_max_tx_power(82); 
    esp_wifi_set_ps(WIFI_PS_NONE); 
    esp_netif_create_default_wifi_ap();
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_deinit());
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    wifi_config_t ap_cfg = {
        .ap = {
            .ssid = "ESP32-Config",
            .password = "config@123",
            .channel = 11,
            .max_connection = 1,
            .authmode = WIFI_AUTH_WPA2_PSK,
            .pmf_cfg = {.required = false}
        }
    };
    memcpy(ap_cfg.ap.ssid, SoftWifiName, strlen(SoftWifiName)); 
    memcpy(ap_cfg.ap.password, SoftWifiPass, strlen(SoftWifiPass));
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_cfg));
    ESP_ERROR_CHECK(esp_wifi_start());

    EventBits_t bits = xEventGroupWaitBits(gs_wificonfig.handle.wifi_event_group, 
        WIFI_AP_START_BIT, 
        pdFALSE, pdFALSE, 
        pdMS_TO_TICKS(AP_START_TIMEOUT_MS));
        
    if (bits & WIFI_AP_START_BIT) {
        ESP_LOGI(TAG, "AP启动成功");
        if (start_webserver() != ESP_OK) {
            ESP_LOGE(TAG, "Web服务启动失败，重启配网模式");
            start_provisioning(timeout);
        }
    } else {
        ESP_LOGE(TAG, "AP启动失败! 建议检查：");
        esp_restart();
    }

    // 设置配网定时器
    if (gs_wificonfig.handle.prov_timer) {
        esp_timer_stop(gs_wificonfig.handle.prov_timer);
        esp_timer_delete(gs_wificonfig.handle.prov_timer);
        gs_wificonfig.handle.prov_timer = NULL;
    }
    esp_timer_create_args_t timer_args = {
        .callback = prov_timeout_cb,
        .name = "prov_timer"
    };
    esp_timer_create(&timer_args, &gs_wificonfig.handle.prov_timer);
    esp_timer_start_once(gs_wificonfig.handle.prov_timer, timeout * 1000000);
}

/* 断开原因解码 */
const char* disconnect_reason(uint8_t reason) {
    switch(reason) {
        case WIFI_REASON_ASSOC_LEAVE:     return "主动断开";
        case WIFI_REASON_AUTH_EXPIRE:     return "认证超时";
        case WIFI_REASON_AUTH_LEAVE:      return "认证离开";
        case WIFI_REASON_ASSOC_EXPIRE:    return "关联超时";
        case WIFI_REASON_ASSOC_TOOMANY:   return "关联过多";
        case WIFI_REASON_NOT_AUTHED:      return "未认证";
        case WIFI_REASON_NOT_ASSOCED:     return "未关联";
        case WIFI_REASON_ASSOC_NOT_AUTHED:return "关联未认证";
        case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: return "4次握手超时";
        case WIFI_REASON_NO_AP_FOUND:     return "AP未找到";
        case WIFI_REASON_AUTH_FAIL:       return "认证失败";
        case WIFI_REASON_CONNECTION_FAIL: return "连接失败";
        default:                          return "未知原因";
    }
}



void Wifi_Init(void)
{
    gs_wificonfig.handle.wifi_event_group = xEventGroupCreate();
    // 初始化WiFi
    wifi_init_config_t wifi_cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&wifi_cfg));
    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));

    // 注册事件处理器
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
    xTaskCreate(connection_monitor_task, "conn_monitor", 3072, NULL, configMAX_PRIORITIES - 1, NULL);

}
